# Maintainer: Sarah Ottinger <schalaalexiazeal@gmail.com>

_realname=llvmlite
pkgbase=mingw-w64-python-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}")
provides=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
conflicts=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
replaces=("${MINGW_PACKAGE_PREFIX}-python3-${_realname}")
pkgver=0.40.1
pkgrel=2
pkgdesc='Lightweight LLVM python binding for writing JIT compilers (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://github.com/numba/llvmlite"
license=('spdx:BSD-2-Clause')
depends=(
  "${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-build"
             "${MINGW_PACKAGE_PREFIX}-python-installer"
             "${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-python-wheel"
             "${MINGW_PACKAGE_PREFIX}-cython"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-llvm-14")
source=("https://pypi.org/packages/source/${_realname::1}/${_realname}/${_realname}-${pkgver}.tar.gz"
        "multi-defs.patch"
        "path_fix.patch")
sha256sums=('5cdb0d45df602099d833d50bd9e81353a5e036242d3c003c5b294fc61d1986b4'
            'b4610934ac8fd7e614d9ea920856ff6da2fbeb146028a664ada8543b8b33ec56'
            '813ecc48f18543f0d36b03c7596a1a6a26be31b9cfa44f1111ac232821844a79')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Nbp1 -i "${srcdir}/$_patch"
  done
}

prepare() {
  cd "$srcdir/${_realname}-${pkgver}"

  apply_patch_with_msg \
    multi-defs.patch \
    path_fix.patch

  sed -i "s,_MSC_VER,_WIN32," ffi/core.h
}

build() {
  cp -r "${_realname}-${pkgver}" "python-build-${MSYSTEM}"
  cd "${srcdir}/python-build-${MSYSTEM}"

  export CMAKE_GENERATOR="Ninja"
  export LLVM_DIR=${MINGW_PREFIX}/opt/llvm-14/lib/cmake/llvm

  ${MINGW_PREFIX}/bin/python -m build --wheel --skip-dependency-check --no-isolation
}

package() {
  cd "${srcdir}/python-build-${MSYSTEM}"

  MSYS2_ARG_CONV_EXCL="--prefix=" \
    ${MINGW_PREFIX}/bin/python -m installer --prefix=${MINGW_PREFIX} \
    --destdir="${pkgdir}" dist/*.whl

  local _py3ver=$(${MINGW_PREFIX}/bin/python -c "import sys;sys.stdout.write('.'.join(map(str, sys.version_info[:2])))")
  install -Dm644 ffi/build/libllvmlite.dll "${pkgdir}${MINGW_PREFIX}/lib/python${_py3ver}/site-packages/llvmlite/binding/llvmlite.dll"

  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/LICENSE"
}
